import 'dart:async';

/**
 * @Description: 计时器工具类
 * @Author: 下雨了
 * @CreateDate: 2022-09-20 16:28
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-09-20 16:28
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */

typedef OnTimeCallback = void Function(String time);

class TimerUtils {
  // 私有构造函数
  TimerUtils._internal();

  // 保存单例
  static final TimerUtils _timerUtils = TimerUtils._internal();

  // 工厂构造函数
  factory TimerUtils() => _timerUtils;

  Timer? timer; // 计时器
  int startSeconds = 0;

  // 开始 返回 00:00:00
  void start(OnTimeCallback onCallback, {int startSecond = 0}) {
    if (timer != null) {
      timer!.cancel();
    }
    String timeStr = "00:00";

    const oneSec = Duration(seconds: 1);

    timer = Timer.periodic(oneSec, (Timer timer) {
      ++startSeconds;
      // 通过秒定义 持续时间
      Duration duration = Duration(seconds: startSeconds);
      // 时
      int hours = duration.inHours;
      // 分
      int minutes = duration.inMinutes - hours * 60;
      // 秒
      int seconds = duration.inSeconds - duration.inMinutes * 60;
      // timeStr = "${fixedIntString(hours)}:${fixedIntString(minutes)}:${fixedIntString(seconds)}";
      timeStr = "${fixedIntString(duration.inMinutes)}:${fixedIntString(seconds)}";
      onCallback.call(timeStr);
    });
  }

  // 暂停
  void pause() {
    cancel();
  }

  // 重新开始
  void restart() {
    start((a) {}, startSecond: startSeconds);
  }

  // 取消
  void cancel() {
    startSeconds = 0;
    timer?.cancel();
  }

  String fixedIntString(
    int a, {
    int fixed = 2,
  }) {
    String str = a.toString();
    if (str.length < fixed) {
      return str.padLeft(fixed, '0');
    }
    return str;
  }
}
